<template>
  <div style="padding: 0px 8px;">
    <div class="upload-tools">
      <file-upload 
        ref="upload"
        v-model="files"
        :accept="accept" 
        :multiple="multiple" 
        :thread="thread"
        :custom-action="customAction"
        @input="updateFile"
        @input-file="inputFile"
        @input-filter="inputFilter">
      </file-upload>
      <a-button icon="upload" style="margin-right: 8px" @click="selectFile">选择文件</a-button>
      <a-button v-show="files.length > 0 && $refs.upload && !$refs.upload.active" @click.prevent="$refs.upload.active = true">上传</a-button>
      <a-button v-show="files.length > 0 && $refs.upload && $refs.upload.active" @click.prevent="$refs.upload.active = false">取消</a-button>
    </div>
    <div class="upload-list" style="margin-top: 8px;">
      <a-list
        size="small"
        itemLayout="vertical"
        :bordered="files.length > 0"
        :data-source="files"
        style="max-height: 274px; overflow-y: auto;"
      >
        <a-list-item slot="renderItem" slot-scope="item">
            <a-row type="flex" align="middle" v-if="!showThumbnail">
              <a-col :span="12" style="font-size: 12px;">
                <a-icon type="file" size="small" style="margin-right: 4px;"></a-icon>
                <span>{{item.name}}</span>
              </a-col>
              <a-col :span="5" justify="center">
                <a-tag>{{formatSize(item.size / 1024)}}</a-tag>
              </a-col>
              <a-col :span="5" style="font-size: 12px;" justify="center">
                <span v-if="item.error" style="color: #f52835;"><b>{{item.error}}</b></span>
                <span v-else-if="item.success">已完成</span>
                <span v-else-if="item.active">上传中</span>
                <span v-else>待上传</span>
              </a-col>
              <a-col :span="2" justify="center" style="font-size: 12px;">
                <a-button size="small" shape="circle" @click.prevent="remove(item)"><a-icon type="delete" style="color: #a2a2a2;"/></a-button>
              </a-col>
            </a-row>
            <a-row type="flex" align="middle" v-if="showThumbnail">
              <a-col :span="3">
                <span>
                  <a-avatar :size="48" shape="square" :src="item.thumb" @click="showImageModal(item.thumb)" style="cursor: pointer;"/>
                </span>
              </a-col>
              <a-col :span="11" style="font-size: 12px;">
                <span>{{item.name}}</span>
              </a-col>
              <a-col :span="4">
                <a-tag>{{formatSize(item.size / 1024)}}</a-tag>
              </a-col>
              <a-col :span="4" style="font-size: 12px;" justify="center">
                <span v-if="item.error" style="color: #f52835;"><b>{{item.error}}</b></span>
                <span v-else-if="item.success">已完成</span>
                <span v-else-if="item.active">上传中</span>
                <span v-else>待上传</span>
              </a-col>
              <a-col :span="2" justify="center" style="font-size: 12px;">
                <a-button size="small" shape="circle" @click.prevent="remove(item)"><a-icon type="delete" style="color: #a2a2a2;"/></a-button>
              </a-col>
            </a-row>
            <a-row type="flex" align="middle" style="margin-top: 8px;">
              <a-progress :percent="Math.round(item.progress)" size="small" v-if="item.error" status="exception" />
              <a-progress :percent="Math.round(item.progress)" size="small" v-else-if="item.success" status="success" />
              <a-progress :percent="Math.round(item.progress)" size="small" v-else-if="item.active" status="active" />
              <a-progress :percent="Math.round(item.progress)" size="small" v-else status="normal" />
            </a-row>
        </a-list-item>
      </a-list>
    </div>
    <image-modal
      ref="imageModal"
      :visible="visibleImageModal"
      @cancel="hideImageModal"
    />
  </div>
</template>

<script>
import ImageModal from './image-modal'
import FileUpload from '@/components/vue-upload-component'
import {formatSize} from '@/utils/util'

export default {
  name: 'Upload',
  components: { FileUpload, ImageModal },
  data() {
    return {
      files: [],
      visibleImageModal: false
    }
  },
  props: {
    showThumbnail: {
      type: Boolean,
    },
    accept: {
      type: String,
    },
    size: {
      type: Number,
      default: 0,
    },
    multiple: {
      type: Boolean,
    },
    maximum: {
      type: Number,
      default() {
        return this.multiple ? 0 : 1
      }
    },
    thread: {
      type: Number,
      default: 1,
    },
    customAction: {
      type: Function,
      default: () => {}
    }
  },
  computed: {

  },
  methods: {
    formatSize,
    showImageModal(url) {
      this.visibleImageModal = true
      this.$refs.imageModal.url = url
    },
    hideImageModal() {
      this.visibleImageModal = false
      this.$refs.imageModal.url = undefined
    },
    selectFile() {
      this.$refs.upload.selectFile()
    },
    remove(file) {
      this.$refs.upload.remove(file)
      this.$emit('handleRemove', file)
    },
    updateFile(file) {
    },
    inputFile(newFile, oldFile) {
    },
    inputFilter(newFile, oldFile, prevent) {
      if (newFile && !oldFile) {
        // 过滤系统文件 和隐藏文件
        if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
          return prevent()
        }
        
        // 过滤 php html js 文件
        if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
          return prevent()
        }
        
        // 过滤 文件名重复的文件
        this.files.filter(item => {
          if (newFile.name == item.name) {
            return prevent()
          }
        })

        // 创建 blob 字段
        newFile.blob = ''
        let URL = (window.URL || window.webkitURL)
        if (URL) {
          newFile.blob = URL.createObjectURL(newFile.file)
        }
                
        // 缩略图
        newFile.thumb = ''
        if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
          newFile.thumb = newFile.blob
        }
        
        // image 尺寸
        if (newFile && newFile.type.substr(0, 6) === "image/") {
          let img = new Image()
          img.onload = () => {
            // console.log('获取到图片的宽高 => ' + img.width + ':' + img.height)
            this.$refs.upload.update(newFile, {error: '', height: img.height, width: img.width})
          } 
          img.src = newFile.blob
        }
        
        // audio 时长
        if (newFile.blob && newFile.type.substr(0, 6) === 'audio/') {
          let audio = new Audio(URL.createObjectURL(newFile.file))
          audio.addEventListener("loadedmetadata", () => {
            // 时长值的获取要等到这个匿名函数执行完毕才产生
            let duration = audio.duration
            // newFile.duration = parseInt(duration)
            this.$refs.upload.update(newFile, {error: '', duration: parseInt(duration)})
            // console.log('获取到音频的时长=> ' + duration)
          })
        }
        
        // video 时长 尺寸
        if (newFile.blob && newFile.type.substr(0, 6) === 'video/') {
          let video = document.createElement('video')
          video.src = URL.createObjectURL(newFile.file)
          video.addEventListener("loadedmetadata", () => {
            // 时长值的获取要等到这个匿名函数执行完毕才产生
            let duration = video.duration
            // newFile.duration = parseInt(duration)
            this.$refs.upload.update(newFile, {error: '', duration: parseInt(duration)})
            // console.log('获取到视频的时长=> ' + duration)
          })
          video.addEventListener("canplay", (e) => {
            // 获取宽高
            let width = e.target.videoWidth
            let height = e.target.videoHeight
            // newFile.width = parseInt(width)
            // newFile.height = parseInt(height)
            this.$refs.upload.update(newFile, {error: '', width: parseInt(width), height: parseInt(height)})
            // console.log('获取到视频的宽高 => ' + e.target.videoWidth + ':' + e.target.videoHeight)
            // console.log('获取到视频的宽高 => ' + width + ':' + height)
          })
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
  /deep/.ant-list-empty-text {
    display: none;
  }
  /deep/.ant-list-bordered {
    border: 1px solid #f0f0f0;
  }
</style>
